let Main = {
    data() {
        return {
            codeNumber: '', //条形码
            Quagga: Quagga,
            dialogFormVisible: false,
            dialogFormPay: false,
            // TODO 测试使用
            isVip: false,
            showInfo: [],
            orderAmount: 0.00,
            discountAmount: 0.00,
            amountToBePaid: 0.00,
            vip: {
                phoneNumber: '',
                code: '',
            },
            phoneNumber: '',
            codeReader: new ZXing.BrowserMultiFormatReader(),
            paymentAction: '',
            bizContent: '',
            out_trade_no: '',
            interval: null,
            isSending: false,
            countdown: 0,
            MemberRegistration: false,
            sendSubDisabled: true,
            integral: 0,
            // 今日热销
            hotSellingList: [],
            newProductList: [],
            preferentialList: [],
        }
    },
    created() {
        this.showCharts();
    },
    mounted(){
        this.generateUserShowQRCode();
    },
    methods: {
        qinit() {
            let _this = this;
            Quagga.init({
                inputStream: {
                    name: "Live",
                    type: "LiveStream",
                    target: document.querySelector('#canvanCode')
                },
                decoder: {
                    readers: ["ean_reader", 'code_39_reader'],
                    debug: {
                        drawBoundingBox: false,
                        showFrequency: false,
                        drawScanline: false,
                        showPattern: false,
                    },
                    multiple: false
                },
                frequency: 1,
            }, () => {
                //打开摄像头
                Quagga.start();
                Quagga.onDetected(function (data) {
                    _this.codeNumber = data.codeResult.code;
                    //data.codeResult.code就是摄像头扫描出的商品条形码
                    if (_this.codeNumber.length === 13) {
                        axios.get("/apm/commodity/queryProduct?codeNumber=" + _this.codeNumber + "&isVip=" + _this.isVip)
                            .then(function (resp) {
                                // 扫描商品成功后添加商品
                                if (resp.data.isSucc) {
                                    _this.$refs.audio.play();
                                    let flag = true;
                                    _this.showInfo.forEach(function (item) {
                                        if (item["barcode"] === resp.data.message.barcode) {
                                            item["count"] += 1;
                                            flag = false;
                                        }
                                    });
                                    if (flag) {
                                        _this.showInfo.push(resp.data.message);
                                    }
                                    _this.orderAmount += resp.data.message["price"];
                                    _this.discountAmount -= resp.data.message["discountPrice"]
                                    _this.amountToBePaid += (resp.data.message["price"] - resp.data.message["discountPrice"]);
                                }
                            }).catch(function (error) {
                            _this.$message.error(error);
                        })
                    }
                });
            });
        },
        qstop() {
            this.dialogFormVisible = false;
            if (null !== this.Quagga) {
                Quagga.stop();
            }
            this.init();
        },
        removeCountInfo(index, rows) {
            this.orderAmount -= rows[index]["price"];
            this.discountAmount += rows[index]["discountPrice"];
            this.amountToBePaid = this.orderAmount + this.discountAmount;
            let count = rows[index]["count"];
            if (count > 1) {
                rows[index]["count"] = count - 1;
            } else {
                rows.splice(index, 1);
            }
        },
        addCountInfo(index, rows) {
            let count = rows[index]["count"];
            rows[index]["count"] = count + 1;
            this.orderAmount += rows[index]["price"];
            this.discountAmount -= rows[index]["discountPrice"];
            this.amountToBePaid = this.orderAmount + this.discountAmount;
        },
        balancePay() {
            this.dialogFormPay = true;
        },
        async openScan() {
            const that = this
            that.codeReader.getVideoInputDevices().then((videoInputDevices) => {
                // 默认获取第一个摄像头设备id
                let firstDeviceId = videoInputDevices[0].deviceId;
                // 获取第一个摄像头设备的名称
                const videoInputDeviceslablestr = JSON.stringify(videoInputDevices[0].label);
                if (videoInputDevices.length > 1) {
                    // 判断是否后置摄像头
                    if (videoInputDeviceslablestr.indexOf('back') > -1) {
                        firstDeviceId = videoInputDevices[0].deviceId;
                    } else {
                        firstDeviceId = videoInputDevices[1].deviceId;
                    }
                }
                that.decodeFromInputVideoFunc(firstDeviceId);
            }).catch((err) => {
                console.error(err);
            });
        },
        decodeFromInputVideoFunc(firstDeviceId) {
            const that = this;
            that.codeReader.reset() // 重置
            that.textContent = null // 重置
            that.codeReader.decodeFromInputVideoDeviceContinuously(firstDeviceId, 'video', (result, err) => {
                that.textContent = null
                if (result) {
                    that.textContent = result.text;
                    that.$refs.audio.play();
                    // 关闭摄像头
                    that.codeReader.reset();
                    that.codeReader.stopContinuousDecode();
                    if (that.textContent) {
                        that.scanCodePayment(that.textContent);
                    }
                }
                if (err && !(err)) {
                    setTimeout(() => {
                    }, 2000)
                    console.error(err);
                }
            });
        },
        scanCodePayment(data) {
            let _this = this;
            axios.post('/apm/pay/showPay', {
                    "order_amount": _this.orderAmount,
                    "discount_amount": _this.discountAmount,
                    "total_amount": _this.amountToBePaid,
                    "subject": "无人超市",
                    "auth_code": data,
                    "userPhone": _this.phoneNumber,
                    "orderDetailsList": _this.showInfo
                }
            ).then(function (resp) {
                if (resp.data.isSuccess === 200) {
                    _this.$message.success("付款成功");
                    _this.init();
                } else {
                    _this.$message.error(response.data.error);
                }
            }).catch(function (e) {
                _this.$message.error(e);
            });
        },
        onPayment() {
            let _this = this;
            if (_this.interval !== null) {
                clearInterval(_this.interval);
                _this.interval = null;
            }
            axios.post('/apm/pay/showPay', {
                    "order_amount": _this.orderAmount,
                    "discount_amount": _this.discountAmount,
                    "total_amount": _this.amountToBePaid,
                    "subject": "无人超市",
                    "userPhone": _this.phoneNumber,
                    "orderDetailsList": _this.showInfo
                }
            ).then(function (response) {
                if (response.data.isSuccess === 200) {
                    let qrUrl = response.data.qr_code;
                    _this.generateQRCode(qrUrl);
                    _this.out_trade_no = response.data.out_trade_no;
                    _this.interval = setInterval(_this.queryPay, 2000);
                } else {
                    _this.$message.error(response.data.error);
                }
            }).catch(function (e) {
                _this.$message.error(e);
            });
        },
        onReceiptPayment() {
            if (this.amountToBePaid === 0) {
                this.$message.error("金额不为0")
                return;
            }
            this.clearCanvas();
            this.openScan();
        },
        queryPay() {
            let _this = this;
            if (_this.out_trade_no !== '' && _this.out_trade_no.toString().length > 12) {
                axios.post('/apm/pay/queryPay?' +
                    "out_trade_no=" + _this.out_trade_no
                ).then(function (response) {
                    if (response.data.isSuccess === 200) {
                        if (response.data.trade_status === "WAIT_BUYER_PAY") {
                            _this.$message.success("扫码成功，请及时支付");
                        }
                        if (response.data.trade_status === "TRADE_SUCCESS") {
                            _this.$message.success("支付成功，祝您生活愉快");
                            _this.dialogFormPay = false;
                            if (null !== _this.interval) {
                                clearInterval(_this.interval);
                                _this.interval = null;
                                _this.init();
                            }
                        }
                        if (response.data.trade_status === "TRADE_CLOSED") {
                            _this.$message.error("超时关闭，请重新支付");
                            _this.dialogFormPay = false;
                            if (null !== _this.interval) {
                                clearInterval(_this.interval);
                                _this.interval = null;
                            }
                        }
                    }
                }).catch(function (e) {
                    _this.$message.error(e);
                });
            }
        },
        paymentCancellation() {
            this.dialogFormPay = false;
            this.codeReader.reset();
            this.codeReader.stopContinuousDecode();
            if (null !== this.interval) {
                clearInterval(this.interval);
                this.interval = null;
            }
        },
        init() {
            this.codeNumber = '';
            this.dialogFormVisible = false;
            this.dialogFormPay = false;
            this.isVip = false;
            this.showInfo = [];
            this.orderAmount = 0.00;
            this.discountAmount = 0.00;
            this.amountToBePaid = 0.00;
            this.vip = {
                code: '',
                phoneNumber: ''
            }
            this.integral = 0;
            this.phoneNumber = '';
            this.paymentAction = '';
            this.bizContent = '';
            this.out_trade_no = '';
            this.isSending = false;
            this.countdown = 0;
            this.MemberRegistration = false;
            this.sendSubDisabled = true;
            if (null !== this.interval) {
                clearInterval(this.interval);
                this.interval = null;
            }
            if (null !== this.Quagga) {
                Quagga.stop();
            }
        },
        sendCode() {
            if (this.countdown > 0 || this.isSending) {
                this.$message.error("请勿连续点击");
                return; // 防止重复点击发送
            }
            if (this.vip.phoneNumber === '' || this.vip.phoneNumber.toString().length !== 11) {
                this.$message.error("电话号码格式错误，请输入正确的电话号码");
                return;
            }
            let _this = this;
            axios.get("/apm/message/sendLoginCode?phoneNumber=" + _this.vip.phoneNumber)
                .then(function (resp) {
                    if (resp.data.isSuccess === 200) {
                        _this.isSending = true;
                        _this.startCountdown();
                        _this.sendSubDisabled = false;
                    } else {
                        _this.$message.error("发送失败，请重新发送");
                    }
                }).catch(function (error) {
                _this.$message.error("发送失败，请重新发送");
            });

        },
        startCountdown() {
            this.isSending = false;
            this.countdown = 60;
            const timer = setInterval(() => {
                this.countdown--;
                if (this.countdown <= 0) {
                    clearInterval(timer);
                }
            }, 1000);
        },
        generateQRCode(text) {
            const qr = new QRious({
                element: this.$refs.qrcodeCanvas,
                value: text,
                size: 300 // 设置二维码大小
            });
        },
        clearCanvas() {
            const canvas = this.$refs.qrcodeCanvas;
            const context = canvas.getContext('2d');

            // 使用clearRect方法清空画布
            context.clearRect(0, 0, canvas.width, canvas.height);
        },
        vipForm() {
            let vip = this.vip;
            if (vip["code"] === '' || vip["phoneNumber"] === '') {
                this.$message.error("验证码和电话号码不为空");
                return;
            }
            let _this = this;
            axios.get('/apm/message/verifyCode?phoneNumber=' + vip["phoneNumber"] + '&code=' + vip["code"])
                .then(function (resp) {
                    if (resp.data.isSuccess === 200) {
                        _this.$message.success("登录成功，请购物");
                        _this.phoneNumber = vip["phoneNumber"];
                        _this.isVip = true;
                        _this.MemberRegistration = false;
                        // _this.sendSubDisabled = true;
                    } else {
                        _this.$message.error("验证码错误，请重试");
                    }
                })
                .catch(function (e) {
                    _this.$message.error(e);
                })
        },
        cancelMember() {
            this.MemberRegistration = false;
            this.sendSubDisabled = true;
            this.vip = {
                code: '',
                phoneNumber: ''
            }
            this.integral = 0;
        },
        // 扫码结算
        settlement() {
            this.dialogFormVisible = true;
            if ("" !== this.phoneNumber) {
                let _this = this;
                axios.get('/apm/user/queryIntegral' + '?phoneNumber=' + _this.phoneNumber)
                    .then(function (resp) {
                        if (resp.data.isSuccess === 200) {
                            _this.integral = resp.data.integral;
                        }
                    }).catch(function (error) {
                    _this.$message.error(error);
                })
            }
        },
        showCharts() {
            let _this = this;
            // 今日优惠
            axios.get('/apm/commodity/queryPreferential')
                .then(function (resp) {
                    _this.preferentialList = resp.data;
                })
                .catch(function (e) {
                    _this.$message.error(e);
                })
            // 热销商品
            axios.get('/apm/queryOrder/queryHotSelling')
                .then(function (resp) {
                    _this.hotSellingList = resp.data;
                })
                .catch(function (e) {
                    _this.$message.error(e);
                })
            // 上新商品
            axios.get('/apm/commodity/newProduct')
                .then(function (resp) {
                    _this.newProductList = resp.data;
                })
                .catch(function (e) {
                    _this.$message.error(e);
                })
            // 客流量折线图
            axios.get('/apm/pay/orderCountToDay')
                .then(function (resp) {
                    myHeatLineChart(resp.data, _this.$refs.ChartOfPassengerFlow);
                })
                .catch(function (e) {
                    _this.$message.error("客流量折线图绘制失败!" + e);
                })
            // 类别销量统计
            axios.get('/apm/queryOrder/queryTypeCount')
                .then(function (resp) {
                    myBarChart(resp.data, _this.$refs.SalesStatistics);
                })
                .catch(function (e) {
                    _this.$message.error("类别销量统计图绘制失败!" + e);
                })
        },
        generateUserShowQRCode() {
            console.log('生成二维码');
            const qr = new QRious({
                element: this.$refs.generateUserShow,
                value: 'https://chipangpang.top/apm/userShow',
                size: 200 // 设置二维码大小
            });
        },
    }
}
let Ctor = Vue.extend(Main)
new Ctor().$mount('#app')

// echarts 绘制折线图
function myHeatLineChart(response, demo) {
    var myChart = echarts.init(demo);
    var option;


    option = {
        xAxis: {
            type: 'category',
            // boundaryGap: false,
            data: response.xAxis,
            axisLabel: {
                color: '#f8f8f8'
            }
        },
        title: {
            left: 'center',
            text: getCurrentDate() + ' 日客流量折线图',
            textStyle: {
                color: '#f8f8f8'
            }
        },
        grid: {
            top: '7%',
            left: '1%',
            right: '1%',
            bottom: '1%',
            containLabel: true
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                color: '#f8f8f8'
            }
        },
        series: [
            {
                data: response.yAxis,
                type: 'line',
                smooth: true,
                lineStyle: {
                    width: 2, // 设置线宽为 2 像素
                    color: '#ebb563',
                },
            }
        ]
    };

    option && myChart.setOption(option);
}

// echarts绘制柱状图

function myBarChart(response, demo) {
    var myChart = echarts.init(demo);
    var option;


    option = {
        xAxis: {
            type: 'category',
            // boundaryGap: false,
            data: response.xAxis,
            axisLabel: {
                color: '#f8f8f8'
            }
        },
        title: {
            left: 'center',
            text: '最受欢迎的类别统计',
            textStyle: {
                color: '#f8f8f8'
            }
            // text: getCurrentDate() + ' 日类别销量统计'
        },
        grid: {
            top: '7%',
            left: '1%',
            right: '1%',
            bottom: '1%',
            containLabel: true
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                color: '#f8f8f8'
            }
        },
        series: [
            {
                data: response.yAxis,
                type: 'bar',
                smooth: true,
                itemStyle: {
                    color: '#ebb563', // 设置固定颜色
                },
            }
        ]
    };

    option && myChart.setOption(option);
}

function getCurrentDate() {
    const today = new Date();
    const year = today.getFullYear();
    const month = (today.getMonth() + 1).toString().padStart(2, '0');
    const day = today.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
}